import { onMounted } from "vue";
import { IMP3Data, mockIMP3Data } from "./useRequest";
export function isAllLatin(str: string) {
	const reg = new RegExp("^[a-zA-Z0-9]+$");
	return reg.test(str);
}

export function smartCompareStr(a: string, b: string) {
	if (a.length !== b.length) {
		return a.length - b.length;
	}

	if (isAllLatin(a) && !isAllLatin(b)) {
		return -1;
	}

	if (!isAllLatin(a) && isAllLatin(b)) {
		return 1;
	}

	return a.localeCompare(b);
}

export function sortStringArr(arr: string[]) {
	return arr.sort((a, b) => smartCompareStr(a, b));
}

export function mergeMP3Data(data?: Partial<IMP3Data>): IMP3Data {
	const mock = mockIMP3Data();

	if (!data) {
		return mock;
	}

	return {
		...mock,
		title: "未命名",
		album: "未知专辑",
		artist: "未知艺术家",
		...data,
	};
}

export function isNotCompleteMp3Data(musicInfo: Partial<IMP3Data>) {
	return !musicInfo.title || !musicInfo.album || !musicInfo.artist;
}

export function getMP3DataImageBuffer(data: IMP3Data): string | null {
	const buffer = (data as any)?.image?.imageBuffer;
	if (buffer) {
		return buffer as string;
	}

	return null;
}

export function setTagDivHeight() {
	const trList = document.querySelectorAll("#show-info tr");
	for (let i = 0; i < trList.length; i++) {
		const tr = trList[i] as HTMLElement;
		const td = tr.firstElementChild as HTMLElement;
		if (td && tr) {
			tr.style["height"] = "auto";
			td.style["height"] = "inherit";
			tr.style["height"] = Math.floor(tr.scrollHeight) + "px";
		}
	}
}

export function splitFilename(file: string) {
	const index = file.lastIndexOf(".");

	const ext = file.slice(index);
	const name = file.slice(0, index);
	return {
		ext,
		name,
	};
}
